﻿namespace LogManager.Core.Models.Smtp
{
    using LogManager.Core.Helpers;
    using LogManager.Utils.Unity;
    using LogManager.Utils.Xml;
    using System.Xml.Linq;
    using LogManager.Core.Factories;

    /// <summary>
    /// Class that represents the smtp configuration
    /// </summary>
    public class SmtpSettings : XmlElementBase, ISmtpSettings
    {
        public const string DEFAULT_TEMPLATE = @"
    <SmtpSettings EnableNotifications='true'>
      " + From.DEFAULT_TEMPLATE + @"
      " + To.DEFAULT_TEMPLATE + @"
      " + SmtpServer.DEFAULT_TEMPLATE + @"
    </SmtpSettings>";

        /// <summary>
        /// Gets or sets the address of the sender
        /// </summary>
        public virtual From From { get; set; }

        /// <summary>
        /// Gets or sets the address of the receivers
        /// </summary>
        public virtual To To { get; set; }

        /// <summary>
        /// Gets or sets the smtp server
        /// </summary>
        public virtual SmtpServer SmtpServer { get; set; }

        public virtual bool EnableNotifications { get; set; }

        public readonly IXmlElementFactory _xmlFactory;

        public SmtpSettings(XElement baseNode, IXmlElementFactory xmlFactory)
            : base(baseNode)
        {
            this._xmlFactory = xmlFactory;
            this.Initialize();
            this.PropertyChanged += (a, b) => SaveChanges();
        }

        private void Initialize()
        {
            var xml = new XmlResolver<SmtpSettings>(BaseNode);
            this.From = xml.ResolveChild(c => c.From, this._xmlFactory.CreateSmtpFrom);
            this.To = xml.ResolveChild(c => c.To, this._xmlFactory.CreateSmtpTo);
            this.SmtpServer = xml.ResolveChild(c => c.SmtpServer, this._xmlFactory.CreateSmtpServer);
            this.EnableNotifications = xml.GetAttributeValue(c => c.EnableNotifications);
        }

        public override void SaveChanges()
        {
            var xml = new XmlResolver<SmtpSettings>(BaseNode);
            xml.SetChild(c => c.From, From);
            xml.SetChild(c => c.To, To);
            xml.SetChild(c => c.SmtpServer, SmtpServer);
            xml.SetAttributeValue(c => c.EnableNotifications, EnableNotifications);
        }

        IFrom ISmtpSettings.From
        {
            get { return this.From; }
        }

        ISmtpServer ISmtpSettings.SmtpServer
        {
            get { return this.SmtpServer; }
        }

        ITo ISmtpSettings.To
        {
            get { return this.To; }
        }
    }
}
